// 发布订阅模式共三个角色信息

class PubSub {
  constructor() {
    this.message = {}
    this.subscribes = {}
  }
  publish (type, message) {
    if (!this.message[type]) {
      this.message[type] = []
    }
    this.message[type].push(message)
    this.notify(type, message)
  }
  subscribe (type, fn) {
    if (!this.subscribes[type]) {
      this.subscribes[type] = []
    }
    this.subscribes[type].push(fn)
  }
  notify (type, message) {
    const subscribes = this.subscribes[type]
    subscribes.length && subscribes.forEach(fn => {
      if (typeof (fn) !== 'function') {
        throw new Error('订阅事件必须是一个函数')
      }
      fn(message)
    })
  }
}
class Publisher {
  constructor(name, pub) {
    this.name = name
    this.pub = pub
  }
  publish (type, message) {
    this.pub.publish(type, message)
  }
}

class Subscriber {
  constructor(name, sub) {
    this.name = name
    this.sub = sub
  }
  subscribe (type, fn) {
    this.sub.subscribe(type, fn)
  }
}

const pubsub = new PubSub()
const publisher = new Publisher('星星', pubsub)

const subscriber1 = new Subscriber('A', pubsub)
const subscriber2 = new Subscriber('B', pubsub)
const subscriber3 = new Subscriber('C', pubsub)
subscriber1.subscribe('news', (message) => {
  console.log('当前A接收到的消息为', message)
})
subscriber2.subscribe('news', (message) => {
  console.log('当前是B,接收到的消息为：', message)
})

publisher.publish('news', '今天水浒将延迟更新一集')